package com.ykt.service;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ykt.cache.UserCache;
import com.ykt.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户服务
 *
 * @author long.hua
 * @version 1.0.0
 * @since 2015-12-09 23:03
 */
public class UserService {
    private final static Logger LOGGER = LoggerFactory.getLogger(UserService.class);


    private User userDao = User.dao;
    private UserCache userCache = Duang.duang(UserCache.class);


    public User find(String phone){
        User user = userCache.get(phone);
        if(user == null){

            // 不存在则查询DB
            user = userDao.findMerchantByPhone(phone);
            userCache.put(phone, user);
        }

        return user;
    }


    public User find(Integer userId){
        String phone  = userCache.getPhone(userId);
        if(StrKit.isBlank(phone)){
            return userDao.findById(userId);
        }

        return find(phone);
    }

    @Before(Tx.class)
    public int save(User user){
        boolean flag = false;

        // 查询如更新用户
        Integer id = user.get("id");
        if(id == null || id < 0){
        	flag = insert(user);//user中没有ID值
            if(!flag){
                LOGGER.warn("Save User error, phone: {}", user.get("phone"));
                return -1;
            }
        } else {
            flag = update(user);
            if(!flag){
                LOGGER.warn("Update User error, phone: {}", user.get("phone"));
                return -1;
            }
        }

        // 不存在则查询DB，插入或更新缓存
        if(flag){
            userCache.put(user.getStr("phone"), user);
        }

        // 返回ID
        return user.get("id");
    }

    private boolean insert(User user){
        return user.save();//直接保存即可
    }

    private boolean update(User user){
        return user.set("name", user.get("name")).set("head", user.get("head")).update();
    }

}
